<?php
/**
 * Created by PhpStorm.
 * User: jiangjunxian
 * Date: 2016/11/30
 * Time: 15:58
 */

namespace app\modules\admin\controllers;


use app\modules\admin\models\Route;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\Response;

class RouteController extends Controller
{
    private $_route = false;

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'create' => ['post'],
                    'assign' => ['post'],
                    'remove' => ['post'],
                    'refresh' => ['post'],
                ]
            ]
        ];
    }

    public function actionIndex() {
        return $this->render('index', ['routes' => $this->getRouteModel()->getRoutes()]);
    }

    public function actionCreate() {
        $routes = \Yii::$app->request->post('routes', '');
        $routes = preg_split('/\s*,\s*/', trim($routes), -1, PREG_SPLIT_NO_EMPTY);
        $route = $this->getRouteModel();
        $route->assign($routes);
        \Yii::$app->response->format = Response::FORMAT_JSON;
        return $route->getRoutes();
    }

    public function actionAssign() {
        $routes = \Yii::$app->request->post('routes', []);
        $route = $this->getRouteModel();
        $route->assign($routes);
        \Yii::$app->response->format = Response::FORMAT_JSON;
        return $route->getRoutes();
    }

    public function actionRemove() {
        $routes = \Yii::$app->request->post('routes', []);
        $route = $this->getRouteModel();
        $route->remove($routes);
        \Yii::$app->response->format = Response::FORMAT_JSON;
        return $route->getRoutes();
    }

    public function actionRefresh() {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        return $this->getRouteModel()->refresh()->getRoutes();
    }

    private function getRouteModel() {
        if($this->_route === false) {
            $this->_route = new Route();
        }

        return $this->_route;
    }

}